import { defineComponent, ref, reactive, computed, onMounted, watch, withModifiers, withDirectives } from 'vue'
import styles from './HelloWorldJsx.module.css'

// 定义自定义指令
const vHighlight = {
  mounted(el) {
    console.log('vHighlight mounted')
    el.style.border = '2px solid blue';
  }
}

export default defineComponent({
  props: {
    msg: String
  },
  directives: {
    highlight: vHighlight
  },
  setup(props, { emit, slots }) {

    // setup中定义指令
    // const vHighlight = {
    //   mounted(el) {
    //     console.log('vHighlight mounted')
    //     el.style.border = '2px solid blue';
    //   }
    // }

    const state = reactive({
      items: ['Vue', 'JSX', 'Composition'],
      isActive: true
    })

    const toggle = () => {
      state.isActive = !state.isActive
    }

    const count = ref(0)
    const step = ref(1)
    // 计算属性
    const doubleCount = computed(() => count.value * 2)
    
    // 事件处理函数
    const increment = () => {
      console.log('---- increment ----:', );
      count.value += step.value
      emit('count-change', count.value)
    }

    const parentClick = () => {
      console.log('---- parentClick ----:', );
      alert('parent click')
    }

    // 监听 count 的变化
    watch(() => count.value, (newVal, oldVal) => {
      console.log(`${props.msg} count changed from ${oldVal} to ${newVal}`)
    })
    
    // 生命钩子
    onMounted(() => {
      console.log(`${props.msg} 组件已经挂载`)
    })
    
    return () => (
      <div class={styles.containerJsx}>
        <h3>Props: {props.msg}</h3>
        <h3 style={{color: state.isActive ? 'blue' : 'black'}}>Step: {step.value} - Count: {count.value}</h3>
        <h3 class={[state.isActive ? styles['double-count-activejsx'] : '']}>Double Count: {doubleCount.value}</h3>
        {/* setup中定义指令使用
        {withDirectives(
          <input 
            type="text"
            v-model={[step.value, ['number']]}
          />
        , [[ vFocus, true]])} */}
        <input 
            type="text"
            v-model={[step.value, ['number']]}
            v-highlight
          />
        <div onClick={parentClick}>
          <button onClick={increment}>增加会冒泡</button>
          <button onClick={withModifiers(() => increment(),['stop'])}>增加阻止冒泡</button>
        </div>
        <button onClick={toggle}>显示与隐藏</button>
        {
          state.isActive && <ul>
          {state.items.map(item => (
              <li key={item}>{item}</li>
            ))}
          </ul>
        }
        {slots.footer && slots.footer({msg: props.msg})}
      </div>
    )
  }
})